/**
************************************************************
* @file         main.c
* @brief        main
* @author       Gizwits
* @date         2018-07-19
* @version      V03030000
* @copyright    Gizwits
*
* @note         机智云.只为智能硬件而生
*               Gizwits Smart Cloud  for Smart Products
*               链接|增值ֵ|开放|中立|安全|自有|自由|生态
*               www.gizwits.com
*
***********************************************************/
#include "gagent_soc.h"
#include "../Gizwits/gizwits_product.h"
#include "../driver/soil.h"
#include "../driver/motor.h"


#define QUERY_INTERVAL 5 //S


TX_TIMER *userTimer;

// 定时器回调
void ICACHE_FLASH_ATTR userTimerCB(void)
{
    static uint8_t ctime = 0;
    static uint8_t ccount = 0;
    int32_t soilValue = 0;
    uint8_t soilPerc = 0; 

    if(QUERY_INTERVAL < ctime) 
    {
        ctime = 0; 
		// 土壤湿度传感器采集
        //soilValue = 0;//user handle 
		soilValue = soilGetValue(); // ADC采集接口函数

        GIZWITS_LOG("========> [devSDK Loop] soilValue=%d, motorSetValue=%d \r\n", soilValue, ccount % 2);

		// 过滤、分压计算
        if(SOIL_RANGEV_MAX < soilValue) 
        {
            soilValue = SOIL_RANGEV_MAX; 
        }
        else if(SOIL_RANGEV_MIN > soilValue) 
        {
            soilValue = SOIL_RANGEV_MIN; 
        }
        soilPerc = soilValue * 100 / (SOIL_RANGEV_MAX - SOIL_RANGEV_MIN); //100:percentage
        currentDataPoint.valuehumidity = soilPerc;
        GIZWITS_LOG( "========> [devSDK Loop] soilPerc=%d,valuemotor = %d\r\n", currentDataPoint.valuehumidity,currentDataPoint.valueMotor);
       
        GIZWITS_LOG( "========> [devSDK Loop] soilLevel = %d%% [MAX:%d; MIN:%d] \r\n", currentDataPoint.valuehumidity, SOIL_RANGEV_MAX, SOIL_RANGEV_MIN);

		// 数据上报
        gizwitsHandle((dataPoint_t *)&currentDataPoint);
        
        ccount++; 
    }
    ctime++;  
}

void sensorInit(void)
{
    int32 ret = -1;
    
    GIZWITS_LOG("Sensor initialization ...\n"); 

    // sensor init  
	// 传感器初始化接口
	soilInit();
	motorInit();

    txm_module_object_allocate(&userTimer, sizeof(TX_TIMER));
    ret = tx_timer_create(userTimer, "userTimer", userTimerCB, NULL, 1,
                          100, TX_AUTO_ACTIVATE);
    if(ret != TX_SUCCESS)
    {
        GIZWITS_LOG("Failed to create UserTimer.\n");
    }
}


void gagentMain( void )
{
    getFreeHeap();
    sensorInit();
    gizwitsInit();
}
